const dayjs = require('dayjs');
import { observable, action } from 'mobx-miniprogram';
import { STATES } from '../../../projects/plm/config/research_state';
import { TRANSITIONS } from '../../../projects/plm/config/research_transition';
import { PERMISSIONS } from '../../../projects/plm/config/research_permission';
import cloudHelper from '../../../helpers/cloud_helper';

/**
 * 研发项目状态机 Store
 * 使用MobX管理状态机状态
 */
export const researchStore = observable({
  // 状态定义
  loading: false,
  error: null,
  currentState: '',
  currentSubState: '',
  projectData: {},
  history: [],
  availableEvents: [],
  stateStack: [], // 保存状态历史栈用于状态回溯
  projectId: '',
  
  /**
   * 初始化状态机
   * @param {String} projectId 项目ID
   */
  initialize: action(async function(projectId) {
    if (!projectId) return;
    
    this.loading = true;
    this.error = null;
    this.projectId = projectId;
    
    try {
      // 从云函数加载当前状态
      const data = await cloudHelper.callCloudData('research/state', { id: projectId });
      
      if (!data) {
        throw new Error('找不到项目状态数据');
      }
      
      // 更新状态数据
      this.currentState = data.status || '';
      this.currentSubState = data.subStatus || '';
      this.projectData = data.formData || {};
      
      // 加载历史记录
      const history = await cloudHelper.callCloudData('research/history', { id: projectId });
      this.history = history || [];
      
      // 初始化状态栈
      this.stateStack = data.stateStack || [];
      
      // 加载可用事件
      this._updateAvailableEvents();
      
      this.error = null;
    } catch (err) {
      this.error = err.message || '初始化状态机失败';
    } finally {
      this.loading = false;
    }
  }),
  
  /**
   * 更新状态数据
   */
  _updateAvailableEvents: action(function() {
    const { currentState, currentSubState } = this;
    
    if (!currentState || !currentSubState) {
      this.availableEvents = [];
      return;
    }
    
    // 查找当前状态可用的转换事件
    const events = TRANSITIONS.filter(transition => 
      transition.from.state.toLowerCase() === currentState.toLowerCase() && 
      transition.from.subState.toLowerCase() === currentSubState.toLowerCase()
    ).map(transition => ({
      event: transition.event,
      toState: transition.to.state,
      toSubState: transition.to.subState,
      roles: transition.roles || []
    }));
    
    this.availableEvents = events;
  }),
  
  /**
   * 触发状态转换
   * @param {String} event 事件名称
   * @param {Object} data 事件数据
   */
  triggerEvent: action(async function(event, data = {}) {
    if (!this.projectId) {
      this.error = '项目ID不能为空';
      return false;
    }
    
    this.loading = true;
    this.error = null;
    
    try {
      // 查找对应的转换规则
      const transition = TRANSITIONS.find(t => 
        t.event === event &&
        t.from.state.toLowerCase() === this.currentState.toLowerCase() && 
        t.from.subState.toLowerCase() === this.currentSubState.toLowerCase()
      );
      
      if (!transition) {
        throw new Error(`无效的状态转换: ${this.currentState}.${this.currentSubState} → ${event}`);
      }
      
      // 验证条件
      if (transition.condition && !transition.condition(data)) {
        throw new Error('状态转换条件不满足');
      }
      
      // 调用云函数执行状态转换
      const result = await cloudHelper.callCloudSumbit('research/transit', {
        id: this.projectId,
        event,
        data,
        from: {
          state: this.currentState,
          subState: this.currentSubState
        },
        to: {
          state: transition.to.state,
          subState: transition.to.subState
        }
      });
      
      // 更新状态
      this.currentState = transition.to.state;
      this.currentSubState = transition.to.subState;
      
      // 保存当前状态到栈
      this.stateStack.push({
        state: this.currentState,
        subState: this.currentSubState,
        timestamp: dayjs().valueOf()
      });
      
      // 更新可用事件
      this._updateAvailableEvents();
      
      // 刷新历史记录
      const history = await cloudHelper.callCloudData('research/history', { id: this.projectId });
      this.history = history || [];
      
      this.loading = false;
      return true;
    } catch (err) {
      this.error = err.message || '状态转换失败';
      this.loading = false;
      return false;
    }
  }),
  
  /**
   * 获取当前状态名称
   */
  getStateName: function() {
    if (!this.currentState || !this.currentSubState) return '';
    
    const mainState = STATES[this.currentState.toUpperCase()];
    if (!mainState) return '';
    
    const subState = mainState.subStates[this.currentSubState.toUpperCase()];
    if (!subState) return mainState.name;
    
    return `${mainState.name} - ${subState.name}`;
  },
  
  /**
   * 重置状态机
   */
  reset: action(function() {
    this.loading = false;
    this.error = null;
    this.currentState = '';
    this.currentSubState = '';
    this.projectData = {};
    this.history = [];
    this.availableEvents = [];
    this.stateStack = [];
    this.projectId = '';
  })
}); 